/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.report.controller;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.RoleBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.common.web.Util;
import com.koron.report.bean.DangerAnalysis;
import com.koron.report.bean.riskanddanger.HiddenDangerDiscoveryDto;
import com.koron.report.service.api.HiddenDangerDiscoveryAnalysisService;
import com.koron.report.util.BusinessCode;
import com.koron.risk.bean.CorpBean;
import com.koron.risk.service.api.CorpManagementService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "dangerAnalysis", description = "隐患统计相关接口")
@RestController("/dangerAnalysis")
@PropertySource("classpath:report.properties")
public class DangerAnalysisController {

    @Autowired
    private CorpManagementService corpManagementService;

    @Autowired
    private HiddenDangerDiscoveryAnalysisService dangerDiscoveryAnalysisService;

    @Autowired
    private Util util;

    @Value("${app.groupLeaderRole}")
    private String groupLeadrRole;


    @ApiOperation("查询隐患列表接口，可根据查询集团、片区，水司，网格，只到网格级")
    @ApiImplicitParams({
            @ApiImplicitParam(name="orgCode",value = "集团/片区/水司/网格编码",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name="updateTimeStart",value = "开始时间",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name="updateTimeEnd",value = "结束时间",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name="page",value = "当前页",dataType = "int",paramType = "query"),
            @ApiImplicitParam(name="pageSize",value = "每页条数",dataType = "int",paramType = "query")
    })
    @RequestMapping(value = "/dangerList.htm",method = RequestMethod.POST)
    public MessageBean<DataBean<HiddenDangerDiscoveryDto>>  queryAllDanger(@RequestParam(required = false) String orgCode, @RequestParam(required = false) final @JsonFormat(pattern="yyyy-MM-dd")
    @DateTimeFormat(pattern="yyyy-MM-dd") Date updateTimeStart, @RequestParam(required = false) final @JsonFormat(pattern="yyyy-MM-dd")
                                                                    @DateTimeFormat(pattern="yyyy-MM-dd")   Date updateTimeEnd, @RequestParam(required = false)Integer page, @RequestParam(required = false)Integer pageSize){
        //根据编码查询当前的隐患编码
        Integer type=dangerDiscoveryAnalysisService.checkLevel(orgCode);
        Integer start = null;
        if(page!=null&&page>0){
            if (pageSize == null || pageSize <= 0) {
                pageSize = 15;
            }
            start = (page <= 1) ? 0 : (page - 1) * pageSize;
        }
        MessageBean<DataBean<HiddenDangerDiscoveryDto>> msg=dangerDiscoveryAnalysisService.hiddenDangerDiscoveryList(type,orgCode,updateTimeStart,updateTimeEnd,start,pageSize);
        if (msg.getData()!=null){
           msg.getData().setPageNo(page);
           msg.getData().setPageSize(pageSize);
        }
        //获取隐患列表
        return msg;
    }

    @ApiOperation("获取统计权限级别，是水司还是片区还是集团")
    @RequestMapping(value = "/checkPermission.htm",method = RequestMethod.POST)
    public MessageBean<Map> checkPermission(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user){
        MessageBean<Map> msg=MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(),Map.class);
        if(null==user){
            msg.setCode(BusinessCode.NOT_LOGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return msg;
        }
        Map<String,Object> dataMap=new HashMap<>();
        //获取当前用户的角色信息
        MessageBean<Map> roleMap = (MessageBean<Map>) util.getRolesAndGroupsByStaff(user.getCode(),1024);
        Map map=roleMap.getData();
        if (!map.isEmpty()){
            List<RoleBean> roleBeanList= (List<RoleBean>) map.get("role");
            //集团领导角色code
            List<String> roleCodeList=new ArrayList<>();
            if (null!=roleBeanList&&roleBeanList.size()>0)
                roleCodeList=roleBeanList.stream().map(RoleBean::getCode).collect(Collectors.toList());
            List<CorpBean> corpBeanList=corpManagementService.corpBeanList();
            if(roleCodeList.contains(groupLeadrRole)){
                //包含集团领导角色
                dataMap.put("roleName","集团领导");
                dataMap.put("roleType",1);
                dataMap.put("roleCode",groupLeadrRole);
                dataMap.put("corpList",corpBeanList);
                msg.setData(dataMap);
                return msg;
            }else{
                //包含水司级统计
                List<CorpBean> corpBeanList1=new ArrayList<>();
                //获取当前登录人所在的水司
                DepartmentTreeBean departmentTreeBean= (DepartmentTreeBean) util.corp(user.getCode()).getData();
                if (null!=departmentTreeBean){
                    CorpBean corpBean=corpManagementService.getOne(departmentTreeBean.getDepartmentCode()).getData();
                    corpBeanList1.add(corpBean);
                }
                dataMap.put("roleName","公司级");
                dataMap.put("roleType",3);
                dataMap.put("districtList",null);
                dataMap.put("corpList",corpBeanList1);
                msg.setData(dataMap);
                return msg;
            }

        }
        return msg;
    }


    @ApiOperation("查询某个层级下各子层级隐患统计分析列表接口，可根据查询集团、水司")
    @ApiImplicitParams({
            @ApiImplicitParam(name="orgCode",value = "集团/片区/水司/网格编码，查询集团是编码可为空",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name="updateTimeStart",value = "开始时间",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name="updateTimeEnd",value = "结束时间",dataType = "String",paramType = "query"),
            @ApiImplicitParam(name="page",value = "当前页",required = true,dataType = "int",paramType = "query"),
            @ApiImplicitParam(name="pageSize",value = "每页条数",required = true,dataType = "int",paramType = "query")
    })
    @RequestMapping(value = "/getDangerAnalysisListByLevel.htm",method = RequestMethod.POST)
    public MessageBean<DataBean<DangerAnalysis>> getDangerAnalysisListByLevel(@RequestParam(required = false) String orgCode, @RequestParam(required = false) final @JsonFormat(pattern="yyyy-MM-dd")
    @DateTimeFormat(pattern="yyyy-MM-dd") Date updateTimeStart, @RequestParam(required = false) final @JsonFormat(pattern="yyyy-MM-dd")
                                                                              @DateTimeFormat(pattern="yyyy-MM-dd")   Date updateTimeEnd, @RequestParam(required = true)Integer page, @RequestParam(required = true)Integer pageSize){

        Integer orgLevel=dangerDiscoveryAnalysisService.checkLevel(orgCode);
        if (orgLevel==null||orgLevel>=2||orgLevel<0){
            MessageBean<DataBean<DangerAnalysis>> msg=new MessageBean<>();
            msg.setCode(BusinessCode.ILEGAL_ORGLEVEL.getCode());
            msg.setDescription(BusinessCode.ILEGAL_ORGLEVEL.getDescription());
            return msg;
        }
        MessageBean<DataBean<DangerAnalysis>> msg=dangerDiscoveryAnalysisService.getDangerAnalysisListByLevel(orgLevel,orgCode,updateTimeStart,updateTimeEnd,page,pageSize);
        return msg;
    }

}
